package com.netpace.iem.ahmed.utilities;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Arrays;
import java.util.Collections;
import java.util.Enumeration;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public class HibernateEntityManager {
	
	private static HibernateEntityManager instance;
	private EntityManagerFactory emf;
	private static EntityManager entityManager; 
	
	private HibernateEntityManager() {
		Thread.currentThread().setContextClassLoader(new ClassLoader() {
	        @Override
	        public Enumeration<URL> getResources(String name) throws IOException {
	            if (name.equals("META-INF/persistence.xml")) {
	                return Collections.enumeration(Arrays.asList(new File("resources/persistence.xml")
	                        .toURI().toURL()));
	            }
	            return super.getResources(name);
	        }
	    });
		emf = Persistence.createEntityManagerFactory("iem");
		entityManager = emf.createEntityManager();
	}
	
	public static EntityManager getEntityManager() {
		if(instance == null)
			synchronized (HibernateEntityManager.class) {
				if(instance == null)
					instance = new HibernateEntityManager();	
			}			
		return entityManager;
	}
	
	public void close() throws Exception {
		emf.close();
	}
	
}
